<!-- The exported code uses Tailwind CSS. Install Tailwind CSS in your dev environment to ensure all styles work. -->
<template>
  <div class="flex-1 flex flex-col h-screen">
    <!-- 顶部操作栏 -->
    <div class="bg-white p-4 border-b flex justify-between items-center">
      <div class="flex items-center">
        <h1 class="text-xl font-bold">AI 绘图</h1>
      </div>
      <div class="flex items-center">
        <span class="text-gray-500 text-sm mr-2">最近生成：{{ latestGenerationTime }}</span>
        <el-button
          type="primary"
          size="small"
          class="!rounded-button whitespace-nowrap"
          @click="loadDrawHistory"
        >
          <el-icon class="mr-1"><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 模型选择标签页 -->
    <div class="bg-white border-b px-6 py-2">
      <el-tabs v-model="currentModel" @tab-change="handleModelChange">
        <el-tab-pane label="Midjourney" name="midjourney">
          <template #label>
            <div class="flex items-center">
              <img
                src="https://cdn-icons-png.flaticon.com/512/5968/5968991.png"
                class="w-5 h-5 mr-2"
                alt="Midjourney"
              />
              Midjourney
            </div>
          </template>
        </el-tab-pane>
        <el-tab-pane label="DALL-E" name="dalle">
          <template #label>
            <div class="flex items-center">
              <img
                src="https://cdn-icons-png.flaticon.com/512/5968/5968389.png"
                class="w-5 h-5 mr-2"
                alt="DALL-E"
              />
              DALL-E
            </div>
          </template>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 主体内容区 -->
    <div class="flex-1 overflow-y-auto p-6 bg-gray-50">
      <!-- 图片生成区域 -->
      <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
        <div class="flex flex-col lg:flex-row gap-6">
          <!-- 左侧生成控制区 -->
          <div class="lg:w-3/5">
            <h2 class="text-lg font-medium mb-4">创建新图像</h2>
            
            <!-- 垫图上传 - 简化版 -->
            <div class="mb-4">
              <label class="block text-gray-700 font-medium mb-2">垫图上传（可选）</label>
              <el-upload
                class="upload-demo border-dashed border-2 border-gray-200 rounded-lg"
                :show-file-list="false"
                :before-upload="beforeImageUpload"
                :http-request="handleImageUpload"
                accept="image/*"
                drag
              >
                <div v-if="!baseImage" class="p-8 text-center">
                  <el-icon class="text-4xl text-gray-400 mb-3"><Upload /></el-icon>
                  <div class="text-gray-600 font-medium">点击或拖拽图片到此处</div>
                  <div class="text-sm text-gray-400 mt-1">支持JPG、PNG格式，不超过10MB</div>
                </div>
                <div v-else class="p-6 text-center">
                  <img :src="baseImage" class="w-24 h-24 object-cover rounded-lg mx-auto mb-2" />
                  <div class="text-green-600 font-medium">垫图已上传</div>
                  <div class="text-sm text-gray-400">点击更换图片</div>
                </div>
              </el-upload>
              
              <div v-if="baseImage" class="mt-3 text-center">
                <el-button type="danger" size="small" plain @click="removeBaseImage">
                  <el-icon class="mr-1"><Delete /></el-icon>移除垫图
                </el-button>
              </div>
            </div>

            <!-- 提示词输入 - 简化版 -->
            <div class="mb-4">
              <div class="flex justify-between items-center mb-2">
                <label class="block text-gray-700 font-medium">描述你想要的图像</label>
                <span class="text-sm text-gray-400">{{ promptLength }}/1000</span>
              </div>
              <el-input
                v-model="prompt"
                type="textarea"
                :rows="4"
                placeholder="描述您想要生成的图像，例如：一只可爱的橘色小猫坐在花园里，阳光明媚，高清摄影风格..."
                maxlength="1000"
                show-word-limit
                class="mb-3"
              />
              
              <!-- 简化的快捷标签 -->
              <div class="flex flex-wrap gap-2">
                <el-tag
                  v-for="tag in [
                    '钢铁侠 Iron Man. Detailed schematic, colour line art, colored 3D main body, annotated labels, dimensions. DSLR camera. Macro lens. Technical illustration. Kodak T-Max 100 film',
                    'A majestic dragon soaring through storm clouds, lightning crackling around its wings, photorealistic, epic fantasy, cinematic lighting, 8K resolution, detailed scales',
                    'Cyberpunk cityscape at night, neon lights reflecting on wet streets, flying cars, holographic advertisements, futuristic architecture, blade runner style, ultra detailed',
                    'Beautiful cherry blossom tree in full bloom, traditional Japanese garden, koi pond, stone lanterns, soft morning light, watercolor painting style, peaceful atmosphere',
                    'Vintage steam locomotive crossing mountain bridge, dramatic sunset sky, detailed metalwork, smoke billowing, golden hour lighting, historical photography style',
                    'Underwater coral reef ecosystem, tropical fish, sea turtles, vibrant colors, crystal clear water, marine life documentary style, National Geographic quality'
                  ]"
                  :key="tag"
                  class="cursor-pointer"
                  size="small"
                  @click="addPromptTag(tag)"
                >
                  {{ tag.length > 40 ? tag.substring(0, 40) + '...' : tag }}
                </el-tag>
              </div>
            </div>

            <!-- 图片尺寸 - 优化大气版 -->
            <div class="mb-6">
              <label class="block text-gray-700 font-semibold mb-4 text-base">选择图片尺寸</label>
              <div class="grid grid-cols-3 gap-4">
                <div
                  v-for="size in imageSizes.slice(0, 3)"
                  :key="size.value"
                  @click="selectedSize = size.value"
                  :class="[
                    'relative cursor-pointer group transition-all duration-300 ease-in-out',
                    'border-2 rounded-xl p-5 bg-gradient-to-br from-white to-gray-50',
                    'hover:shadow-lg hover:scale-105 hover:border-blue-300',
                    selectedSize === size.value 
                      ? 'border-blue-500 bg-gradient-to-br from-blue-50 to-indigo-50 shadow-md scale-105' 
                      : 'border-gray-200'
                  ]"
                >
                  <!-- 选中状态指示器 -->
                  <div 
                    v-if="selectedSize === size.value"
                    class="absolute -top-2 -right-2 w-6 h-6 bg-blue-500 rounded-full flex items-center justify-center shadow-lg"
                  >
                    <el-icon class="text-white text-sm"><Check /></el-icon>
                  </div>
                  
                  <!-- 图标和标题 -->
                  <div class="text-center">
                    <!-- 图形预览 -->
                    <div class="mb-3 flex justify-center">
                      <div 
                        :class="[
                          'border-2 border-gray-300 bg-gray-100 transition-colors duration-200',
                          size.value === '1:1' ? 'w-8 h-8 rounded-lg' : 
                          size.value === '9:16' ? 'w-6 h-10 rounded-md' : 
                          'w-10 h-6 rounded-md',
                          selectedSize === size.value ? 'border-blue-400 bg-blue-100' : ''
                        ]"
                      ></div>
                    </div>
                    
                    <h3 :class="[
                      'font-semibold text-base mb-1 transition-colors duration-200',
                      selectedSize === size.value ? 'text-blue-700' : 'text-gray-800'
                    ]">
                      {{ size.label }}
                    </h3>
                    
                    <p :class="[
                      'text-sm transition-colors duration-200',
                      selectedSize === size.value ? 'text-blue-600' : 'text-gray-500'
                    ]">
                      {{ size.dimensions }}
                    </p>
                    
                    <!-- 使用场景提示 -->
                    <p :class="[
                      'text-xs mt-2 font-medium transition-colors duration-200',
                      selectedSize === size.value ? 'text-blue-500' : 'text-gray-400'
                    ]">
                      {{ size.value === '1:1' ? '头像·社交' : 
                         size.value === '9:16' ? '手机·竖屏' : 
                         '横幅·宽屏' }}
                    </p>
                  </div>
                  
                  <!-- 悬浮效果光晕 -->
                  <div 
                    :class="[
                      'absolute inset-0 rounded-xl transition-opacity duration-300',
                      'bg-gradient-to-br from-transparent to-blue-100/20',
                      'opacity-0 group-hover:opacity-100'
                    ]"
                  ></div>
                </div>
              </div>
              
              <!-- 尺寸说明 -->
              <div class="mt-3 text-center">
                <p class="text-sm text-gray-500">
                  选择合适的尺寸比例，获得最佳的视觉效果
                </p>
              </div>
            </div>

            <!-- 生成按钮 -->
            <div class="mt-6">
              <el-button
                type="primary"
                size="large"
                @click="generateImage"
                :loading="generating"
                :disabled="!prompt.trim()"
                class="w-full h-12 text-base font-medium"
              >
                <el-icon v-if="!generating" class="mr-2"><Picture /></el-icon>
                {{ generating ? '生成中...' : '开始生成图像' }}
              </el-button>
              
              <div v-if="!prompt.trim()" class="text-center text-sm text-gray-400 mt-2">
                请输入图像描述后开始生成
              </div>
            </div>
          </div>

          <!-- 右侧预览区 -->
          <div class="lg:w-2/5">
            <h2 class="text-lg font-medium mb-4">预览</h2>
            <div
              class="border border-gray-200 rounded-lg overflow-hidden bg-gray-50 flex items-center justify-center"
              style="min-height: 350px"
            >
              <div v-if="generating && !generatedImage" class="text-center p-10">
                <!-- 队列中状态 -->
                <div v-if="currentTaskStatus === -1">
                  <el-icon class="text-4xl text-orange-500 mb-4"><Loading /></el-icon>
                  <p class="text-gray-500">任务已加入队列</p>
                  <p class="text-sm font-medium text-orange-600 mt-2">
                    当前状态: {{ getTaskStatusText(currentTaskStatus) }}
                  </p>
                  <p class="text-xs text-gray-400 mt-1">等待系统空闲时进行处理</p>
                </div>
                <!-- 待生成状态 -->
                <div v-else-if="currentTaskStatus === 0">
                  <el-icon class="text-4xl text-yellow-500 mb-4"><Loading /></el-icon>
                  <p class="text-gray-500">任务已提交，等待开始</p>
                  <p class="text-sm font-medium text-yellow-600 mt-2">
                    当前状态: {{ getTaskStatusText(currentTaskStatus) }}
                  </p>
                  <p class="text-xs text-gray-400 mt-1">正在准备绘制您的创意</p>
                </div>
                <!-- 生成中状态 -->
                <div v-else>
                  <el-icon class="animate-spin text-4xl text-blue-500 mb-4"><Loading /></el-icon>
                  <p class="text-gray-500">AI 正在绘制您的创意...</p>
                  <p class="text-sm font-medium text-blue-600 mt-2">
                    当前状态: {{ getTaskStatusText(currentTaskStatus) }}
                  </p>
                  <p class="text-sm text-gray-400 mt-1">当前进度：{{ remainingTime }}%</p>
                </div>
                <p class="text-xs text-gray-400 mt-2">
                  使用 {{ currentModel === 'midjourney' ? 'Midjourney' : 'DALL-E' }} 模型
                </p>
                <el-button
                  @click="cancelGeneration"
                  type="danger"
                  size="small"
                  class="mt-4 !rounded-button"
                >
                  取消生成
                </el-button>
              </div>
              <div v-else-if="generatedImage" class="w-full h-full relative">
                <img :src="generatedImage" alt="生成的图片" class="w-full h-full object-contain" />

                <!-- 图片生成中的进度条覆盖层 -->
                <div
                  v-if="generating && currentTaskStatus === 1"
                  class="absolute bottom-0 left-0 right-0 bg-black/50 text-white p-2"
                >
                  <div class="flex items-center justify-between mb-1">
                    <span class="text-sm">生成中</span>
                    <span class="text-sm">{{ remainingTime }}%</span>
                  </div>
                  <el-progress
                    :percentage="remainingTime"
                    :stroke-width="10"
                    status="warning"
                    class="!mt-1"
                  />
                </div>
              </div>
              <div v-else class="text-center p-10">
                <el-icon class="text-6xl text-gray-300 mb-4"><Picture /></el-icon>
                <p class="text-gray-500">输入提示词并点击生成按钮<br />创建您的 AI 图像</p>
                <p class="text-xs text-gray-400 mt-2">
                  当前使用 {{ currentModel === 'midjourney' ? 'Midjourney' : 'DALL-E' }} 模型
                </p>
              </div>
            </div>

            <!-- 图片操作按钮 -->
            <div v-if="generatedImage" class="mt-4 flex justify-between">
              <div>
                <el-button
                  type="primary"
                  @click="downloadImage"
                  class="!rounded-button whitespace-nowrap"
                  :disabled="generating && currentTaskStatus !== 2"
                >
                  <el-icon class="mr-1"><Download /></el-icon>
                  下载
                </el-button>
                <el-button
                  @click="shareImage"
                  class="!rounded-button whitespace-nowrap"
                  :disabled="generating && currentTaskStatus !== 2"
                >
                  <el-icon class="mr-1"><Share /></el-icon>
                  分享
                </el-button>
              </div>
              <el-button
                @click="regenerateImage"
                class="!rounded-button whitespace-nowrap"
                :disabled="generating && currentTaskStatus !== 2"
              >
                <el-icon class="mr-1"><RefreshRight /></el-icon>
                重新生成
              </el-button>
            </div>

            <!-- 图片参数信息 -->
            <div v-if="generatedImage" class="mt-4 bg-gray-50 p-3 rounded-lg text-sm text-gray-500">
              <div class="flex justify-between mb-1">
                <span>AI模型：</span>
                <span>{{ currentModel === 'midjourney' ? 'Midjourney' : 'DALL-E' }}</span>
              </div>
              <div class="flex justify-between mb-1" v-if="currentModel === 'midjourney'">
                <span>风格：</span>
                <span>{{ getStyleLabel(selectedStyle) }}</span>
              </div>
              <div class="flex justify-between mb-1">
                <span>尺寸：</span>
                <span>{{ getSizeLabel(selectedSize) }}</span>
              </div>
              <div class="flex justify-between mb-1">
                <span>生成时间：</span>
                <span>{{ generatedAt }}</span>
              </div>
              <div class="flex justify-between">
                <span>图片 ID：</span>
                <span class="truncate ml-2" style="max-width: 200px">{{ imageId }}</span>
              </div>

              <!-- Midjourney参数信息 -->
              <template
                v-if="
                  currentModel === 'midjourney' &&
                  (selectedMjParams.quality !== '1' ||
                    selectedMjParams.version !== 'default' ||
                    selectedMjParams.chaosValue > 0)
                "
              >
                <div class="border-t border-gray-200 my-2 pt-2">
                  <div class="font-medium text-gray-700 mb-1">MJ参数:</div>

                  <div
                    v-if="selectedMjParams.quality !== '1'"
                    class="flex justify-between text-xs mb-1"
                  >
                    <span>质量:</span>
                    <span>{{
                      mjParamsData.qualities.find((q) => q.value === selectedMjParams.quality)
                        ?.label || selectedMjParams.quality
                    }}</span>
                  </div>

                  <div
                    v-if="selectedMjParams.version !== 'default'"
                    class="flex justify-between text-xs mb-1"
                  >
                    <span>版本:</span>
                    <span>{{
                      mjParamsData.versions.find((v) => v.value === selectedMjParams.version)
                        ?.label || selectedMjParams.version
                    }}</span>
                  </div>

                  <div
                    v-if="!isV61Version() && selectedMjParams.stylizeValue !== 100"
                    class="flex justify-between text-xs mb-1"
                  >
                    <span>风格化强度:</span>
                    <span>{{ selectedMjParams.stylizeValue }}</span>
                  </div>

                  <div
                    v-if="selectedMjParams.chaosValue > 0"
                    class="flex justify-between text-xs mb-1"
                  >
                    <span>混沌值:</span>
                    <span>{{ selectedMjParams.chaosValue }}</span>
                  </div>

                  <div
                    v-if="selectedMjParams.weirdValue > 0"
                    class="flex justify-between text-xs mb-1"
                  >
                    <span>怪异度:</span>
                    <span>{{ selectedMjParams.weirdValue }}</span>
                  </div>

                  <div v-if="selectedMjParams.isTile" class="flex justify-between text-xs mb-1">
                    <span>平铺:</span>
                    <span>开启</span>
                  </div>

                  <div v-if="selectedMjParams.seed" class="flex justify-between text-xs mb-1">
                    <span>种子值:</span>
                    <span>{{ selectedMjParams.seed }}</span>
                  </div>
                </div>
              </template>
            </div>
          </div>
        </div>
      </div>

      <!-- 历史记录区域 -->
      <div ref="history" class="bg-white rounded-lg shadow-sm p-6">
        <div class="flex justify-between items-center mb-4">
          <h2 class="text-lg font-medium">历史记录</h2>
          <div class="flex items-center">
            <el-select v-model="historyFilter" placeholder="筛选" size="small" class="mr-2 w-28">
              <el-option label="全部" value="all" />
              <el-option label="生成成功" value="success" />
              <el-option label="生成中" value="generating" />
              <el-option label="待生成" value="pending" />
              <el-option label="生成失败" value="failed" />
              <el-option label="Midjourney" value="midjourney" />
              <el-option label="DALL-E" value="dalle" />
            </el-select>
            <el-select v-model="historySortBy" placeholder="排序" size="small" class="mr-2 w-28">
              <el-option label="最新优先" value="newest" />
              <el-option label="最早优先" value="oldest" />
            </el-select>
            <el-button
              type="primary"
              size="small"
              class="!rounded-button whitespace-nowrap"
              @click="loadDrawHistory"
            >
              <el-icon class="mr-1"><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>

        <!-- 图片网格 -->
        <div
          v-if="historyImages.length > 0"
          class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4"
        >
          <div v-for="image in historyImages" :key="image.id" class="relative group">
            <div
              class="aspect-square overflow-hidden border border-gray-200 rounded-lg bg-gray-50 cursor-pointer"
            >
              <!-- 添加状态叠加层，根据任务状态显示不同样式 -->
              <div 
                v-if="image.status != 2 && image.status != '2'" 
                class="absolute inset-0 flex flex-col items-center justify-center z-50"
                :class="{
                  'bg-yellow-900/80 text-white': image.status == -1 || image.status == '-1',
                  'bg-gray-900/80 text-white animate-pulse': image.status == 0 || image.status == '0',
                  'bg-gray-900/80 text-white': image.status == 1 || image.status == '1',
                  'bg-red-900/80 text-white': image.status == 3 || image.status == '3'
                }"
                :style="{ 
                  backgroundColor: (image.status == 0 || image.status == '0') ? 'rgba(31, 41, 55, 0.9) !important' : undefined,
                  border: (image.status == 0 || image.status == '0') ? '2px solid yellow' : undefined
                }"
              >

                
                <!-- 队列中状态 -->
                <div v-if="image.status == -1 || image.status == '-1'" class="text-center p-3">
                  <el-icon class="text-3xl mb-2"><Loading /></el-icon>
                  <div class="font-medium">队列中</div>
                  <div class="text-xs mt-2">任务在队列中，等待系统处理</div>
                </div>
                
                <!-- 待生成状态 -->
                <div v-else-if="image.status == 0 || image.status == '0'" class="text-center p-3">
                  <el-icon class="text-4xl mb-3 animate-bounce text-yellow-400"><Loading /></el-icon>
                  <div class="font-bold text-lg text-yellow-300">等待生成</div>
                  <div class="text-sm mt-2 bg-yellow-600/50 px-2 py-1 rounded">任务已提交，等待处理</div>
                </div>
                
                <!-- 生成中状态 -->
                <div v-else-if="image.status == 1 || image.status == '1'" class="text-center p-3 w-full">
                  <el-icon class="animate-spin text-3xl mb-2"><Loading /></el-icon>
                  <div class="font-medium">生成中</div>
                  <div class="text-xs mt-2">进度：{{ image.progress || '0' }}%</div>
                  <el-progress 
                    v-if="image.progress" 
                    :percentage="Number(image.progress)" 
                    :stroke-width="4" 
                    class="w-3/4 mx-auto mt-2"
                  />
                </div>
                
                <!-- 生成失败状态 -->
                <div v-else-if="image.status == 3 || image.status == '3'" class="text-center p-3">
                  <el-icon class="text-3xl mb-2"><CircleClose /></el-icon>
                  <div class="font-medium">生成失败</div>
                  <div class="text-xs mt-2 px-2 line-clamp-3">{{ image.failReason || '未知错误' }}</div>
                </div>
                
                <!-- 兜底显示 - 显示所有非成功状态 -->
                <div v-else class="text-center p-3">
                  <el-icon class="text-3xl mb-2 text-orange-400"><Warning /></el-icon>
                  <div class="font-medium">未知状态</div>
                  <div class="text-xs mt-2">状态值: {{ image.status }}</div>
                </div>
              </div>
              
              <img
                v-if="image.url"
                :src="image.url"
                :alt="image.prompt"
                class="w-full h-full object-cover hover:scale-105 transition-transform"
                :class="{'opacity-30': image.status !== 2}"
                @click="viewHistoryImage(image)"
              />
              <div 
                v-else 
                class="w-full h-full flex items-center justify-center bg-gray-200"
                @click="viewHistoryImage(image)"
              >
                <el-icon class="text-gray-400 text-4xl"><Picture /></el-icon>
              </div>
            </div>
            <div class="mt-2 text-xs text-gray-500 truncate" :title="image.prompt">
              {{ image.prompt }}
            </div>
            <div class="flex justify-between mt-1 text-xs text-gray-400">
              <span>{{ image.createdAt }}</span>
              <span>{{ image.size }}</span>
            </div>
            
            <!-- Midjourney 操作按钮 -->
            <div v-if="image.status === 2 && image.buttons && image.buttons.length > 0" class="mt-2">
              <div class="grid grid-cols-2 gap-1">
                <button
                  v-for="(button, btnIndex) in image.buttons.slice(0, 4)"
                  :key="btnIndex"
                  @click.stop="handleMjButton(image, button)"
                  class="px-2 py-1 text-xs bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors truncate"
                  :title="button.label"
                >
                  {{ button.label || '操作' }}
                </button>
              </div>
              <div v-if="image.buttons.length > 4" class="mt-1">
                <button
                  @click.stop="showAllButtons(image)"
                  class="w-full px-2 py-1 text-xs bg-gray-500 text-white rounded hover:bg-gray-600 transition-colors"
                >
                  更多操作 ({{ image.buttons.length - 4 }}+)
                </button>
              </div>
            </div>
            <div
              class="absolute top-2 left-2 px-2 py-1 rounded-md text-xs font-medium z-[60]"
              :class="{
                'bg-orange-500 text-white': image.status == -1 || image.status == '-1',
                'bg-yellow-500 text-white animate-pulse shadow-lg': image.status == 0 || image.status == '0',
                'bg-blue-500 text-white': image.status == 1 || image.status == '1',
                'bg-red-500 text-white': image.status == 3 || image.status == '3'
              }"
            >
              {{ getTaskStatusText(image.status) }}
            </div>
            <div
              class="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity flex z-[60]"
            >
              <el-button
                type="info"
                size="small"
                circle
                class="!mr-1"
                @click.stop="downloadHistoryImage(image)"
                :disabled="image.status !== 2"
              >
                <el-icon><Download /></el-icon>
              </el-button>
              <el-button
                type="primary"
                size="small"
                circle
                class="!mr-1"
                @click.stop="reusePrompt(image.prompt)"
              >
                <el-icon><CopyDocument /></el-icon>
              </el-button>
              <el-button type="danger" size="small" circle @click.stop="deleteHistoryImage(image)">
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
        </div>

        <!-- 暂无数据 -->
        <div v-else class="py-8 text-center text-gray-500">
          <el-icon class="text-4xl mb-2"><Picture /></el-icon>
          <p>暂无历史记录</p>
        </div>

        <!-- 分页器 -->
        <div v-if="totalImages > pageSize" class="mt-6 flex justify-center">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="totalImages"
            :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </div>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="previewDialogVisible" width="80%" destroy-on-close>
      <div class="flex flex-col md:flex-row">
        <div class="md:w-3/5">
          <!-- 显示任务状态和进度或失败原因 -->
          <div v-if="previewImage.status !== 2" class="relative">
            <!-- 状态覆盖层 -->
            <div class="absolute inset-0 flex flex-col items-center justify-center z-10"
              :class="{
                'bg-gray-900/70 text-white': previewImage.status === 0 || previewImage.status === 1,
                'bg-red-900/70 text-white': previewImage.status === 3
              }">
              
              <!-- 状态覆盖层 -->
              <div class="absolute inset-0 flex flex-col items-center justify-center z-10"
                :class="{
                  'bg-orange-900/70 text-white': previewImage.status === -1,
                  'bg-gray-900/70 text-white': previewImage.status === 0 || previewImage.status === 1,
                  'bg-red-900/70 text-white': previewImage.status === 3
                }">
                
                <!-- 队列中状态 -->
                <div v-if="previewImage.status === -1" class="text-center p-5">
                  <el-icon class="text-5xl mb-4"><Loading /></el-icon>
                  <div class="text-xl font-medium mb-2">队列中</div>
                  <div class="text-sm">任务在队列中，等待系统空闲时处理</div>
                </div>
                
                <!-- 待生成状态 -->
                <div v-else-if="previewImage.status === 0" class="text-center p-5">
                  <el-icon class="text-5xl mb-4"><Loading /></el-icon>
                  <div class="text-xl font-medium mb-2">等待生成</div>
                  <div class="text-sm">任务已提交，等待处理</div>
                </div>
              </div>
              
              <img 
                v-if="previewImage.url"
                :src="previewImage.url" 
                :alt="previewImage.prompt" 
                class="w-full rounded-lg opacity-40"
              />
              <div 
                v-else 
                class="w-full rounded-lg bg-gray-200 flex items-center justify-center"
                style="height: 300px;"
              >
                <el-icon class="text-gray-400 text-6xl"><Picture /></el-icon>
              </div>
            </div>
            
            <img 
              v-if="previewImage.url"
              :src="previewImage.url" 
              :alt="previewImage.prompt" 
              class="w-full rounded-lg" 
            />
            <div 
              v-else 
              class="w-full rounded-lg bg-gray-200 flex items-center justify-center"
              style="height: 300px;"
            >
              <el-icon class="text-gray-400 text-6xl"><Picture /></el-icon>
            </div>
          </div>
          
          <!-- 成功状态的图片 -->
          <div v-else>
            <img 
              v-if="previewImage.url"
              :src="previewImage.url" 
              :alt="previewImage.prompt" 
              class="w-full rounded-lg" 
            />
            <div 
              v-else 
              class="w-full rounded-lg bg-gray-200 flex items-center justify-center"
              style="height: 300px;"
            >
              <el-icon class="text-gray-400 text-6xl"><Picture /></el-icon>
            </div>
          </div>
        </div>
        <div class="md:w-2/5 md:pl-6 mt-4 md:mt-0">
          <h3 class="text-xl font-medium mb-2">图片信息</h3>
          <!-- 显示任务状态 -->
          <div v-if="previewImage.status !== undefined" class="mb-4">
            <div class="text-gray-500 mb-1">状态</div>
            <div 
              class="p-2 rounded-lg text-sm text-white font-medium"
              :class="{
                'bg-yellow-500': previewImage.status === 0,
                'bg-blue-500': previewImage.status === 1,
                'bg-green-500': previewImage.status === 2,
                'bg-red-500': previewImage.status === 3
              }"
            >
              {{ getTaskStatusText(previewImage.status) }}
              <span v-if="previewImage.status === 1">
                ({{ previewImage.progress || '0' }}%)
              </span>
            </div>
          </div>
          
          <!-- 显示失败原因 -->
          <div v-if="previewImage.status === 3" class="mb-4">
            <div class="text-gray-500 mb-1">失败原因</div>
            <div class="bg-gray-50 p-2 rounded-lg text-sm text-red-600">
              {{ previewImage.failReason || '未知错误' }}
            </div>
          </div>
          
          <div class="mb-4">
            <div class="text-gray-500 mb-1">提示词</div>
            <div class="bg-gray-50 p-3 rounded-lg text-sm break-words">
              {{ previewImage.prompt }}
            </div>
          </div>
          <div class="mb-4 grid grid-cols-2 gap-2">
            <div>
              <div class="text-gray-500 mb-1">尺寸</div>
              <div class="bg-gray-50 p-2 rounded-lg text-sm">{{ previewImage.size }}</div>
            </div>
            <div>
              <div class="text-gray-500 mb-1">风格</div>
              <div class="bg-gray-50 p-2 rounded-lg text-sm">{{ previewImage.style }}</div>
            </div>
            <div>
              <div class="text-gray-500 mb-1">生成时间</div>
              <div class="bg-gray-50 p-2 rounded-lg text-sm">{{ previewImage.createdAt }}</div>
            </div>
            <div>
              <div class="text-gray-500 mb-1">ID</div>
              <div class="bg-gray-50 p-2 rounded-lg text-sm truncate">{{ previewImage.id }}</div>
            </div>
          </div>
          <div class="flex mt-6">
            <el-button
              type="primary"
              @click="downloadPreviewImage"
              class="!rounded-button whitespace-nowrap"
              :disabled="previewImage.status !== 2"
            >
              <el-icon class="mr-1"><Download /></el-icon>
              下载图片
            </el-button>
            <el-button @click="reusePreviewPrompt" class="!rounded-button whitespace-nowrap ml-2">
              <el-icon class="mr-1"><CopyDocument /></el-icon>
              使用提示词
            </el-button>
            <el-button 
              type="danger" 
              @click="deletePreviewImage"
              class="!rounded-button whitespace-nowrap ml-2"
            >
              <el-icon class="mr-1"><Delete /></el-icon>
              删除图片
            </el-button>
          </div>
         
          <!-- Midjourney 操作按钮 -->
          <div v-if="previewImage.status === 2 && previewImage.buttons && previewImage.buttons.length > 0" class="mt-4">
            <h4 class="text-sm font-medium text-gray-700 mb-2">Midjourney 操作</h4>
            <div class="grid grid-cols-2 gap-2">
              <el-button
                v-for="(button, btnIndex) in previewImage.buttons"
                :key="btnIndex"
                size="small"
                @click="handleMjButton(previewImage, button)"
                class="!rounded-button text-xs"
                :title="button.label"
              >
                {{ button.label || '操作' }}
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 分享对话框 -->
    <el-dialog v-model="shareDialogVisible" title="分享图片" width="400px" destroy-on-close>
      <div class="text-center">
        <img
          :src="generatedImage"
          alt="Share Image"
          class="w-full max-h-60 object-contain mb-4 rounded"
        />
        <el-input v-model="shareLink" readonly>
          <template #append>
            <el-button @click="copyShareLink">复制</el-button>
          </template>
        </el-input>
        <div class="grid grid-cols-4 gap-4 mt-6">
          <div
            v-for="platform in sharePlatforms"
            :key="platform.name"
            class="flex flex-col items-center cursor-pointer hover:opacity-80"
            @click="shareTo(platform.name)"
          >
            <el-icon :class="['text-2xl mb-1', platform.iconClass]">
              <component :is="platform.icon"></component>
            </el-icon>
            <span class="text-xs">{{ platform.label }}</span>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, watch, onUnmounted,h } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import {
  User,
  Lock,
  Setting,
  ChatDotRound,
  Picture,
  VideoPlay,
  Medal,
  Ticket,
  ShoppingCart,
  Document,
  Collection,
  Upload,
  Back,
  Refresh,
  Download,
  Share,
  Delete,
  ZoomIn,
  RefreshRight,
  CopyDocument,
  PictureFilled,
  Loading,
  ChatLineRound,
  Position,
  Link,
  CircleCheck,
  CircleClose,
  Check,
  Warning,
} from '@element-plus/icons-vue'
// 提示词相关
const prompt = ref('')
import { useRouter1 } from '../utils/useRoute'
import {
  submitMjDrawTask,
  submitDallEDrawTask,
  queryMjTaskProgress,
  getDrawTaskPage,
  type MjTaskResult,
  type DrawTaskResult,
  deleteDrawTask,
  executeMjCommand,
} from '@/api/ai'

const {
  goToHome,
  goToDocumentUpload,
  goToKnowledgeBaseManagement,
  goToMemberCenter,
  goToNotificationSettings,
  goToOrder,
  goToPointsManagement,
  goToSecuritySettings,
  goToUser,
  goToAiChat,
  goToAiDrawing,
  goToProduct,
} = useRouter1()

// Midjourney参数数据
const mjParamsData = {
  // 图片宽高比参数
  aspectRatios: [
    { value: 'default', label: '默认' },
    { value: '1:1', label: '1:1 (方形)' },
    { value: '16:9', label: '16:9 (横幅)' },
    { value: '9:16', label: '9:16 (竖幅)' },
    { value: '4:3', label: '4:3 (标准)' },
    { value: '3:4', label: '3:4 (竖向标准)' },
    { value: '3:2', label: '3:2 (风景)' },
    { value: '2:3', label: '2:3 (人像)' },
  ],
  // 风格描述标签，替换旧的style参数
  styleDescriptions: [
    { value: 'photorealistic', label: '照片真实感' },
    { value: 'oil painting', label: '油画风格' },
    { value: 'watercolor', label: '水彩画风' },
    { value: 'digital art', label: '数字艺术' },
    { value: 'pencil sketch', label: '铅笔素描' },
    { value: 'anime style', label: '动漫风格' },
    { value: 'pixel art', label: '像素艺术' },
    { value: 'cinematic lighting', label: '电影光效' },
    { value: 'unfiltered, realistic details', label: '无风格滤镜(raw)' },
  ],
  // 图像质量选项
  qualities: [
    { value: '1', label: '标准 (默认)' },
    { value: '2', label: '高质量' },
    { value: '0.5', label: '低质量 (更快)' },
    { value: '0.25', label: '超低质量 (最快)' },
  ],
  // 模型版本
  versions: [
    { value: 'default', label: '默认模型' },
    { value: '6.1', label: 'v6.1 (最新版)' },
    { value: '6', label: 'v6' },
    { value: '5.2', label: 'v5.2' },
    { value: '5.1', label: 'v5.1' },
    { value: '5', label: 'v5' },
    { value: '4', label: 'v4' },
  ],
  // 摄影/艺术风格
  photoStyles: [
    { value: 'photography', label: '摄影风格' },
    { value: 'cinematic', label: '电影风格' },
    { value: 'anime', label: '动漫风格' },
    { value: 'oil painting', label: '油画风格' },
    { value: 'watercolor', label: '水彩画风格' },
    { value: '3D render', label: '3D渲染风格' },
    { value: 'pixel art', label: '像素艺术风格' },
  ],
  // 光照与氛围
  lightings: [
    { value: 'golden hour', label: '黄金时段光线' },
    { value: 'blue hour', label: '蓝调时分光线' },
    { value: 'dramatic lighting', label: '戏剧性光线' },
    { value: 'soft lighting', label: '柔和光线' },
    { value: 'neon lighting', label: '霓虹灯光效果' },
  ],
  // 美学修饰词
  aestheticTerms: [
    { value: 'highly detailed', label: '高度细节' },
    { value: 'intricate details', label: '复杂细节' },
    { value: '8k resolution', label: '8K分辨率' },
    { value: 'photorealistic', label: '照片级真实' },
    { value: 'hyperrealistic', label: '超真实' },
    { value: 'volumetric lighting', label: '体积光' },
    { value: 'ray tracing', label: '光线追踪' },
    { value: 'bokeh effect', label: '景深虚化' },
    { value: 'shallow depth of field', label: '浅景深' },
    { value: 'glossy', label: '光泽质感' },
    { value: 'matte', label: '哑光质感' },
    { value: 'metallic', label: '金属质感' },
  ],
}

// 选中的参数
const selectedMjParams = ref({
  aspectRatio: 'default',
  styleDescription: '',
  quality: '1',
  version: 'default',
  photoStyle: '',
  lighting: '',
  aestheticTerms: [] as string[],
  stylizeValue: 100,
  chaosValue: 0,
  weirdValue: 0,
  isTile: false,
  excludeElements: '',
  seed: '',
})
const history = ref<HTMLElement | null>(null)
const promptLength = computed(() => prompt.value.length)
const promptTags = ref([
  '高清',
  '精致细节',
  '写实风格',
  '梦幻色彩',
  '科技感',
  '自然光',
  '暗调',
  '明亮',
])
// 图片风格
const selectedStyle = ref('realistic')
const imageStyles = ref([
  {
    value: 'realistic',
    label: '写实风格',
    image:
      'https://readdy.ai/api/search-image?query=A%2520photorealistic%2520landscape%2520with%2520mountains%2520and%2520a%2520lake%2520at%2520sunset%252C%2520extremely%2520detailed%2520and%2520lifelike%252C%2520with%2520natural%2520lighting%2520and%2520shadows%252C%2520high%2520resolution%2520photograph%2520style%252C%2520professional%2520photography%252C%2520sharp%2520focus&width=200&height=150&seq=2&orientation=landscape',
  },
  {
    value: 'anime',
    label: '动漫风格',
    image:
      'https://readdy.ai/api/search-image?query=Anime%2520style%2520illustration%2520of%2520a%2520character%2520with%2520colorful%2520hair%2520in%2520a%2520fantasy%2520setting%252C%2520vibrant%2520colors%252C%2520clean%2520lines%252C%2520expressive%2520eyes%252C%2520stylized%2520proportions%252C%2520Japanese%2520animation%2520aesthetic%252C%2520detailed%2520background&width=200&height=150&seq=3&orientation=landscape',
  },
  {
    value: 'watercolor',
    label: '水彩画风',
    image:
      'https://readdy.ai/api/search-image?query=Watercolor%2520painting%2520of%2520flowers%2520in%2520a%2520vase%252C%2520soft%2520color%2520bleeding%252C%2520transparent%2520layers%252C%2520visible%2520brush%2520strokes%252C%2520paper%2520texture%252C%2520artistic%2520style%252C%2520delicate%2520details%252C%2520traditional%2520watercolor%2520technique&width=200&height=150&seq=4&orientation=landscape',
  },
  {
    value: 'oil',
    label: '油画风格',
    image:
      'https://readdy.ai/api/search-image?query=Oil%2520painting%2520of%2520a%2520dramatic%2520seascape%2520with%2520crashing%2520waves%252C%2520thick%2520textured%2520paint%252C%2520visible%2520brush%2520strokes%252C%2520rich%2520colors%252C%2520classical%2520painting%2520style%252C%2520canvas%2520texture%252C%2520dramatic%2520lighting&width=200&height=150&seq=5&orientation=landscape',
  },
  {
    value: 'digital',
    label: '数字艺术',
    image:
      'https://readdy.ai/api/search-image?query=Digital%2520art%2520of%2520a%2520futuristic%2520cityscape%2520with%2520neon%2520lights%252C%2520smooth%2520gradients%252C%2520high%2520contrast%252C%2520vibrant%2520colors%252C%2520detailed%2520textures%252C%2520clean%2520edges%252C%2520modern%2520digital%2520painting%2520style%252C%2520sci-fi%2520atmosphere&width=200&height=150&seq=6&orientation=landscape',
  },
  {
    value: 'sketch',
    label: '素描风格',
    image:
      'https://readdy.ai/api/search-image?query=Pencil%2520sketch%2520of%2520a%2520portrait%252C%2520detailed%2520shading%252C%2520fine%2520lines%252C%2520graphite%2520texture%252C%2520realistic%2520proportions%252C%2520traditional%2520drawing%2520technique%252C%2520paper%2520texture%252C%2520black%2520and%2520white%252C%2520high%2520contrast&width=200&height=150&seq=7&orientation=landscape',
  },
  {
    value: 'abstract',
    label: '抽象艺术',
    image:
      'https://readdy.ai/api/search-image?query=Abstract%2520art%2520with%2520geometric%2520shapes%2520and%2520bold%2520colors%252C%2520non-representational%2520composition%252C%2520vibrant%2520color%2520blocks%252C%2520dynamic%2520lines%252C%2520modern%2520abstract%2520expressionism%252C%2520contemporary%2520art%2520style&width=200&height=150&seq=8&orientation=landscape',
  },
  {
    value: '3d',
    label: '3D 渲染',
    image:
      'https://readdy.ai/api/search-image?query=3D%2520rendered%2520scene%2520of%2520a%2520futuristic%2520interior%252C%2520ray-traced%2520lighting%252C%2520realistic%2520textures%252C%2520reflective%2520surfaces%252C%2520ambient%2520occlusion%252C%2520depth%2520of%2520field%252C%2520high%2520quality%2520CGI%252C%2520photorealistic%2520render&width=200&height=150&seq=9&orientation=landscape',
  },
])
// 图片尺寸
const selectedSize = ref('1:1')
const imageSizes = ref([
  {
    value: '1:1',
    label: '正方形',
    dimensions: '1024 × 1024',
  },
  {
    value: '9:16',
    label: '竖向',
    dimensions: '576 × 1024',
  },
  {
    value: '16:9',
    label: '横向',
    dimensions: '1024 × 576',
  },
  {
    value: '4:3',
    label: '标准',
    dimensions: '1024 × 768',
  },
])
// 高级设置
const generationCount = ref(1)
const negativePrompt = ref('')
const creativityLevel = ref(50)
// 生成状态
const generating = ref(false)
const remainingTime = ref(30)
const generatedImage = ref('')
const generatedAt = ref('')
const imageId = ref('')
// 当前任务状态
const currentTaskStatus = ref<number>(0) // 0:待生成 1:生成中 2:生成成功 3:生成失败
// 历史记录
const historyFilter = ref('all')
const historySortBy = ref('newest')
const currentPage = ref(1)
const pageSize = ref(10)
const totalImages = ref(0)
const historyImages = ref([])
const isLoadingHistory = ref(false)

// 模型标签页
const currentModel = ref('midjourney')
// 预览对话框
const previewDialogVisible = ref(false)
const previewImage = ref({
  id: '',
  url: '',
  prompt: '',
  createdAt: '',
  size: '',
  style: '',
  status: 2, // 默认为成功状态
  progress: '0',
  failReason: '',
})
// 分享对话框
const shareDialogVisible = ref(false)
const shareLink = ref('https://ai.example.com/share/img_123456789')
const sharePlatforms = ref([
  { name: 'wechat', label: '微信', icon: 'ChatLineRound', iconClass: 'text-green-600' },
  { name: 'weibo', label: '微博', icon: 'Position', iconClass: 'text-red-600' },
  { name: 'link', label: '复制链接', icon: 'Link', iconClass: 'text-blue-600' },
  { name: 'download', label: '下载', icon: 'Download', iconClass: 'text-gray-600' },
])

// 添加垫图相关的状态
const baseImage = ref('')
const baseImageArray = ref<string[]>([])

// 图片上传前的验证
const beforeImageUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  
  if (baseImage.value) {
    ElMessage.warning('最多只能上传1张垫图，请先移除当前垫图')
    return false
  }
  
  return true
}

// 处理图片上传
const handleImageUpload = (options: any) => {
  const file = options.file
  const reader = new FileReader()
  
  reader.onload = (e) => {
    if (e.target) {
      // 获取base64字符串
      const base64String = e.target.result as string
      // 设置预览图
      baseImage.value = base64String
      // 提取base64数据部分（去掉前缀如"data:image/jpeg;base64,"）
      const base64Data = base64String.split(',')[1]
      // 存储为数组形式
      baseImageArray.value = [base64Data]
      
      ElMessage.success('垫图上传成功')
    }
  }
  
  reader.readAsDataURL(file)
}

// 移除垫图
const removeBaseImage = () => {
  baseImage.value = ''
  baseImageArray.value = []
  ElMessage.success('已移除垫图')
}

// 以下是各种方法定义
const addPromptTag = (tag) => {
  // 直接替换整个prompt，而不是追加
  prompt.value = tag
}

const getStyleLabel = (value: string) => {
  const style = imageStyles.value.find((s) => s.value === value)
  return style ? style.label : ''
}

const getSizeLabel = (value: string) => {
  const size = imageSizes.value.find((s) => s.value === value)
  return size ? `${size.label} (${size.dimensions})` : ''
}

// 绘图任务ID
const drawTaskId = ref<number | null>(null)
// 任务自定义ID
const customTaskId = ref<string>('')
// 绘图轮询定时器
const drawPollingTimer = ref<number | null>(null)

// 任务状态映射
const taskStatusMap = {
  '-1': '队列中', // 在任务队列中
  0: '等待开始', // 待生成
  1: '生成中', // 生成中
  2: '生成成功', // 生成成功
  3: '生成失败', // 生成失败
}

// 获取任务状态显示文本
const getTaskStatusText = (status: number | undefined): string => {
  if (status === undefined) return '未知状态'
  return taskStatusMap[status as keyof typeof taskStatusMap] || '未知状态'
}

// 生成图片
const generateImage = async () => {
  if (!prompt.value.trim()) {
    ElMessage.warning('请输入提示词')
    return
  }

  generating.value = true
  remainingTime.value = 0 // 初始化进度为0%
  currentTaskStatus.value = 0 // 设置初始状态为待生成
  generatedImage.value = '' // 清空之前的图片

  try {
    // 准备请求参数
    const fullPrompt = currentModel.value === 'midjourney' ? buildFullPrompt() : prompt.value
    console.log('完整的提示词:', fullPrompt)

    const params = {
      prompt: fullPrompt,
      ratio: selectedSize.value,
      // 添加垫图参数
      base64Array: baseImageArray.value.length > 0 ? baseImageArray.value : undefined
    }

    console.log('发送参数:', { ...params, base64Array: baseImageArray.value.length > 0 ? '有垫图数据' : '无垫图数据' })

    // 根据当前选择的模型发送请求
    if (currentModel.value === 'midjourney') {
      const response = await submitMjDrawTask(params)
      console.log('任务提交结果:', response)

      // 检查响应中是否有taskId
      if (response && response.taskId) {
        // 保存任务ID
        drawTaskId.value = response.taskId

        // 开始轮询任务结果
        startPollingDrawResult()
        ElMessage.success('绘图任务已提交，请等待结果')
      } else {
        ElMessage.error('提交绘图任务失败: 未返回任务ID')
        generating.value = false
      }
    } else {
      // DALL-E逻辑
      const response = await submitDallEDrawTask(params)

      if (response && response.taskId) {
        // 保存任务ID
        drawTaskId.value = response.taskId

        // 开始轮询任务结果
        startPollingDrawResult()
        ElMessage.success('绘图任务已提交，请等待结果')
      } else {
        ElMessage.error('提交绘图任务失败: 未返回任务ID')
        generating.value = false
      }
    }
  } catch (error) {
    console.error('提交绘图任务出错:', error)
    ElMessage.error('提交绘图任务出错')
    generating.value = false
  }
}

// 开始轮询绘图结果
const startPollingDrawResult = () => {
  // 清除可能存在的之前的定时器
  if (drawPollingTimer.value !== null) {
    clearInterval(drawPollingTimer.value)
  }

  // 设置轮询间隔（每3秒查询一次）
  drawPollingTimer.value = setInterval(async () => {
    try {
      if (!drawTaskId.value) {
        clearInterval(drawPollingTimer.value as number)
        return
      }

      console.log('查询任务进度:', drawTaskId.value)
      const response = await queryMjTaskProgress(drawTaskId.value)
      console.log('任务进度结果:', response)

      // 确保响应有效
      if (response) {
        const taskData = response
        console.log('任务数据:', taskData)

        // 直接更新任务状态
        currentTaskStatus.value = taskData.status || 0
        console.log('当前状态:', currentTaskStatus.value)

        // 更新进度信息
        if (taskData.progress) {
          const progressText = taskData.progress.toString().replace('%', '')
          const progressNum = parseInt(progressText)
          if (!isNaN(progressNum)) {
            remainingTime.value = progressNum
            console.log('当前进度:', progressNum, '%')
          }
        }

        // 如果图片URL可用，更新图片
        if (taskData.imgList && taskData.imgList.length > 0) {
          generatedImage.value = taskData.imgList[0]
          console.log('图片URL已更新:', taskData.imgList[0])
        }

        // 根据任务状态处理
        if (taskData.status === 2) {
          // 生成成功
          // 清除轮询
          clearInterval(drawPollingTimer.value as number)
          drawPollingTimer.value = null

          // 设置生成时间和ID
          const now = new Date()
          const finishTime = taskData.updateTime ? new Date(taskData.updateTime) : now
          generatedAt.value = finishTime.toLocaleString()

          imageId.value = taskData.id?.toString() || '未知ID'

          // 完成生成
          generating.value = false
          ElMessage.success('图片生成成功')
          // 加载最新历史记录
          loadDrawHistory()
        }
        // 任务失败
        else if (taskData.status === 3) {
          // 生成失败
          clearInterval(drawPollingTimer.value as number)
          drawPollingTimer.value = null
          generating.value = false
          ElMessage.error(`图片生成失败: ${taskData.failReason || '未知错误'}`)
        }
        // 其他状态继续轮询
      } else {
        console.error('查询任务进度失败: 返回数据格式不正确', response)
      }
    } catch (error) {
      console.error('查询绘图结果出错:', error)
    }
  }, 3000)
}

// 重新生成图片
const regenerateImage = () => {
  // 重置状态
  drawTaskId.value = null
  if (drawPollingTimer.value !== null) {
    clearInterval(drawPollingTimer.value)
    drawPollingTimer.value = null
  }
  // 使用相同的提示词重新生成
  generateImage()
}

const downloadImage = () => {
  if (!generatedImage.value) return
  // 模拟下载
  ElMessage.success('图片下载中...')
  // 实际应用中应该创建一个a标签并触发点击
  const link = document.createElement('a')
  link.href = generatedImage.value
  link.download = `AI-Image-${imageId.value}.png`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

const shareImage = () => {
  if (!generatedImage.value) return
  shareDialogVisible.value = true
}

const viewHistoryImage = (image) => {
  previewImage.value = { 
    ...image,
    // 确保包含状态相关字段
    status: image.status || 2,
    progress: image.progress || '0',
    failReason: image.failReason || '未知错误'
  }
  previewDialogVisible.value = true
}

const downloadHistoryImage = (image: any) => {
  // 模拟下载
  ElMessage.success('图片下载中...')
  // 实际应用中应该创建一个a标签并触发点击
  const link = document.createElement('a')
  link.href = image.url
  link.download = `AI-Image-${image.id}.png`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

const deleteHistoryImage = (image) => {
  ElMessageBox.confirm('确定要删除这张图片吗？此操作不可恢复。', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        // 调用删除API
        const loading = ElLoading.service({
          lock: true,
          text: '正在删除...',
          background: 'rgba(0, 0, 0, 0.7)',
        })
        
        // API返回直接是data数据
        const result = await deleteDrawTask(parseInt(image.id))
        loading.close()
        
        // 删除成功
        // 从列表中移除该图片
        historyImages.value = historyImages.value.filter((img) => img.id !== image.id)
        ElMessage.success('图片已删除')
        
        // 重新加载历史记录以更新总数
        loadDrawHistory()
      } catch (error) {
        console.error('删除图片出错:', error)
        ElMessage.error('删除图片出错，请稍后重试')
      }
    })
    .catch(() => {
      // 取消删除
    })
}

const reusePrompt = (promptText: string) => {
  prompt.value = promptText
  // 滚动到生成区域
  scrollToGenerator()
}

const scrollToGenerator = () => {
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

const handlePageChange = (page: number) => {
  currentPage.value = page
  loadDrawHistory()
}

const downloadPreviewImage = () => {
  downloadHistoryImage(previewImage.value)
}

const reusePreviewPrompt = () => {
  prompt.value = previewImage.value.prompt
  previewDialogVisible.value = false
  scrollToGenerator()
}

const copyShareLink = () => {
  navigator.clipboard
    .writeText(shareLink.value)
    .then(() => {
      ElMessage.success('链接已复制到剪贴板')
    })
    .catch(() => {
      ElMessage.error('复制失败，请手动复制')
    })
}

const shareTo = (platform: string) => {
  ElMessage.success(
    `已分享到${platform === 'wechat' ? '微信' : platform === 'weibo' ? '微博' : '其他平台'}`,
  )
  if (platform === 'download') {
    downloadImage()
  }
  shareDialogVisible.value = false
}

const handleModelChange = () => {
  // 根据不同模型，更新尺寸选项
  updateSizeOptions()
}

// 更新尺寸选项
const updateSizeOptions = () => {
  if (currentModel.value === 'midjourney') {
    imageSizes.value = [
      {
        value: '1:1',
        label: '正方形',
        dimensions: '1024 × 1024',
      },
      {
        value: '9:16',
        label: '竖向',
        dimensions: '576 × 1024',
      },
      {
        value: '16:9',
        label: '横向',
        dimensions: '1024 × 576',
      },
      {
        value: '4:3',
        label: '标准',
        dimensions: '1024 × 768',
      },
    ]
  } else {
    // DALL-E 尺寸
    imageSizes.value = [
      {
        value: '1:1',
        label: '正方形',
        dimensions: '1024 × 1024',
      },
      {
        value: '2:3',
        label: '竖向',
        dimensions: '640 × 960',
      },
      {
        value: '3:2',
        label: '横向',
        dimensions: '960 × 640',
      },
    ]
  }
  // 默认选第一个尺寸
  selectedSize.value = imageSizes.value[0].value
}

// 在组件卸载时清除轮询定时器和其他资源
onUnmounted(() => {
  if (drawPollingTimer.value !== null) {
    clearInterval(drawPollingTimer.value)
    drawPollingTimer.value = null
  }
})

// 监听模型切换，更新尺寸选项
watch(currentModel, () => {
  updateSizeOptions()
})

onMounted(() => {
  // 初始化页面
  updateSizeOptions()
  // 加载历史记录
  loadDrawHistory()
})

// 取消当前生成任务
const cancelGeneration = () => {
  if (drawPollingTimer.value !== null) {
    clearInterval(drawPollingTimer.value)
    drawPollingTimer.value = null
  }

  generating.value = false
  remainingTime.value = 0
  drawTaskId.value = null
  currentTaskStatus.value = 0 // 重置状态为待生成

  ElMessage.info('已取消当前绘图任务')
}

// 复制完整Prompt
const copyFullPrompt = () => {
  const fullPrompt = buildFullPrompt()
  navigator.clipboard
    .writeText(fullPrompt)
    .then(() => {
      ElMessage.success('已复制完整提示词到剪贴板')
    })
    .catch(() => {
      ElMessage.error('复制失败，请手动复制')
    })
}

// 监听宽高比变化，同步更新selectedSize
watch(
  () => selectedMjParams.value.aspectRatio,
  (newAspectRatio) => {
    if (newAspectRatio === 'default') return

    // 将MJ宽高比映射到图片尺寸
    if (newAspectRatio === '1:1') {
      selectedSize.value = '1:1'
    } else if (newAspectRatio === '16:9') {
      selectedSize.value = '16:9'
    } else if (newAspectRatio === '9:16') {
      selectedSize.value = '9:16'
    } else if (newAspectRatio === '4:3') {
      selectedSize.value = '4:3'
    } else if (newAspectRatio === '3:4') {
      selectedSize.value = '3:4'
    } else if (newAspectRatio === '3:2') {
      selectedSize.value = '3:2'
    } else if (newAspectRatio === '2:3') {
      selectedSize.value = '2:3'
    }
  },
)

// 监听图片尺寸变化，同步更新宽高比
watch(
  () => selectedSize.value,
  (newSize) => {
    if (currentModel.value !== 'midjourney') return

    // 将图片尺寸映射到MJ宽高比
    selectedMjParams.value.aspectRatio = newSize
  },
)

// 获取当前进度百分比（用于进度条展示）
const getProgressPercentage = (): number => {
  // 如果有明确的进度数值
  if (currentTaskStatus.value === 1 && typeof remainingTime.value === 'number') {
    // 确保进度值在0-100之间
    return Math.min(Math.max(remainingTime.value, 0), 100)
  }

  // 根据状态给出估计进度
  switch (currentTaskStatus.value) {
    case 0:
      return 5
    case 1:
      return 50 // 默认值，当没有具体进度时
    case 2:
      return 100
    case 3:
      return 100
    default:
      return 0
  }
}

// 获取当前进度文本
const getCurrentProgress = (): string => {
  if (currentTaskStatus.value === 1 && typeof remainingTime.value === 'number') {
    return `${remainingTime.value}%`
  }
  return '0%'
}

// 构建完整的Prompt
const buildFullPrompt = (): string => {
  let fullPrompt = prompt.value.trim()

  // 添加风格描述（用于替代旧的--style参数）
  if (selectedMjParams.value.styleDescription) {
    fullPrompt += ', ' + selectedMjParams.value.styleDescription
  }

  // 添加美学修饰词
  if (selectedMjParams.value.aestheticTerms.length > 0) {
    fullPrompt += ', ' + selectedMjParams.value.aestheticTerms.join(', ')
  }

  // 添加摄影/艺术风格
  if (selectedMjParams.value.photoStyle) {
    fullPrompt += ', ' + selectedMjParams.value.photoStyle
  }

  // 添加光照与氛围
  if (selectedMjParams.value.lighting) {
    fullPrompt += ', ' + selectedMjParams.value.lighting
  }

  // 添加参数部分
  let params = ''

  // 宽高比
  if (selectedMjParams.value.aspectRatio !== 'default') {
    params += ` --ar ${selectedMjParams.value.aspectRatio}`
  }

  // 版本
  if (selectedMjParams.value.version !== 'default') {
    params += ` --v ${selectedMjParams.value.version}`
  }

  // 质量
  if (selectedMjParams.value.quality !== '1') {
    params += ` --q ${selectedMjParams.value.quality}`
  }

  // 风格化强度 (仅当版本不是v6.1时才添加)
  if (selectedMjParams.value.stylizeValue !== 100 && !isV61Version()) {
    params += ` --s ${selectedMjParams.value.stylizeValue}`
  }

  // 随机性/混沌值
  if (selectedMjParams.value.chaosValue > 0) {
    params += ` --c ${selectedMjParams.value.chaosValue}`
  }

  // 怪异度
  if (selectedMjParams.value.weirdValue > 0) {
    params += ` --weird ${selectedMjParams.value.weirdValue}`
  }

  // 可平铺
  if (selectedMjParams.value.isTile) {
    params += ' --tile'
  }

  // 种子值
  if (selectedMjParams.value.seed) {
    params += ` --seed ${selectedMjParams.value.seed}`
  }

  // 排除元素
  if (selectedMjParams.value.excludeElements.trim()) {
    params += ` --no ${selectedMjParams.value.excludeElements}`
  }

  return fullPrompt + params
}

// 检查当前是否使用v6.1版本
const isV61Version = (): boolean => {
  return selectedMjParams.value.version === '6.1'
}

// 应用风格描述
const applyStyleDescription = () => {
  // 确保不要重复添加
  if (
    selectedMjParams.value.styleDescription &&
    !prompt.value.includes(selectedMjParams.value.styleDescription)
  ) {
    ElMessage.success('已应用风格描述')
  }
}

// 添加风格描述标签
const applyStyleDescriptionTag = (tag: string) => {
  if (!selectedMjParams.value.styleDescription.includes(tag)) {
    selectedMjParams.value.styleDescription =
      selectedMjParams.value.styleDescription.trim() +
      (selectedMjParams.value.styleDescription ? ', ' : '') +
      tag
    ElMessage.success(`已添加风格: ${tag}`)
  }
}

// 监听版本变化，当选择v6.1时移除不兼容参数
watch(
  () => selectedMjParams.value.version,
  (newVersion) => {
    if (newVersion === '6.1') {
      // v6.1不支持--style和--stylize参数，提示用户
      ElMessage.info('Midjourney v6.1不支持--style和--stylize参数，请使用风格描述来控制图像风格')
    }
  },
)

// 加载绘图历史记录
const loadDrawHistory = async () => {
  const loadingInstance = ElLoading.service({
    target: history.value,
    text: '加载中',
  })
  try {

    // 准备请求参数
    const params = {
      page: {
        page: currentPage.value,
        limit: pageSize.value,
        order: historySortBy.value === 'newest' ? 'DESC' : 'ASC',
        field: 'create_time',
      },
    }

    // 发送请求
    const response = await getDrawTaskPage(params)
    console.log('绘图历史记录:', response)

    // 处理响应数据
    if (response) {
      const { data, totalCount } = response

      // 更新总数和历史记录
      totalImages.value = totalCount

      // 转换数据格式
      const historyData = data.map((item) => {
        // 获取图片URL
        const imgUrl = item.imgList && item.imgList.length > 0 ? item.imgList[0] : ''

        // 获取尺寸
        let sizeText = '未知尺寸'
        if (item.ratio) {
          const ratio = item.ratio
          if (ratio === '1:1') sizeText = '1024 × 1024'
          else if (ratio === '9:16') sizeText = '576 × 1024'
          else if (ratio === '16:9') sizeText = '1024 × 576'
          else if (ratio === '4:3') sizeText = '1024 × 768'
          else if (ratio === '3:4') sizeText = '768 × 1024'
          else if (ratio === '3:2') sizeText = '1024 × 682'
          else if (ratio === '2:3') sizeText = '682 × 1024'
        }

        // 创建时间格式化
        const createTime = item.createTime ? new Date(item.createTime).toLocaleString() : '未知时间'

        return {
          id: item.id?.toString() || '未知ID',
          url: imgUrl,
          prompt: item.prompt || '无提示词',
          createdAt: createTime,
          size: sizeText,
          style: '未知风格', // 暂无风格数据
          // 添加任务状态相关字段
          status: item.status, // 默认为成功状态
          progress: item.progress ? item.progress.toString().replace('%', '') : '0',
          failReason: item.failReason || '未知错误',
          buttons: item.buttons || [],
        }
      })

      // 筛选数据
      historyImages.value =
        historyFilter.value === 'all'
          ? historyData
          : historyData.filter((item) => {
              // 根据任务状态筛选
              if (historyFilter.value === 'success') return item.status === 2;
              if (historyFilter.value === 'generating') return item.status === 1;
              if (historyFilter.value === 'pending') return item.status === 0;
              if (historyFilter.value === 'failed') return item.status === 3;
              
              // 这里暂时无法根据模型类型过滤，因为API返回数据中没有模型类型
              // 如果后续API返回中包含模型类型，可以在此处添加过滤逻辑
              return true
            })
    } else {
      ElMessage.error('加载历史记录失败: ' + (response?.message || '未知错误'))
      historyImages.value = []
    }
  } catch (error) {
    console.error('加载历史记录出错:', error)
    ElMessage.error('加载历史记录出错')
    historyImages.value = []
  } finally {
    loadingInstance.close()
  }
}

// 处理页码变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1 // 重置到第一页
  loadDrawHistory()
}

// 监听排序和筛选变化
watch([historySortBy, historyFilter], () => {
  loadDrawHistory()
})

// 计算最近生成时间
const latestGenerationTime = computed(() => {
  if (historyImages.value.length > 0) {
    return historyImages.value[0].createdAt
  }
  return '无记录'
})

const deletePreviewImage = () => {
  ElMessageBox.confirm('确定要删除这张图片吗？此操作不可恢复。', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        // 调用删除API
        const loading = ElLoading.service({
          lock: true,
          text: '正在删除...',
          background: 'rgba(0, 0, 0, 0.7)',
        })
        
        // API返回直接是data数据
        const result = await deleteDrawTask(parseInt(previewImage.value.id))
        loading.close()
        
        // 删除成功
        // 从列表中移除该图片
        historyImages.value = historyImages.value.filter((img) => img.id !== previewImage.value.id)
        ElMessage.success('图片已删除')
        
        // 关闭预览对话框
        previewDialogVisible.value = false
        
        // 重新加载历史记录以更新总数
        loadDrawHistory()
      } catch (error) {
        console.error('删除图片出错:', error)
        ElMessage.error('删除图片出错，请稍后重试')
      }
    })
    .catch(() => {
      // 取消删除
    })
}

// 处理Midjourney按钮点击
const handleMjButton = async (image, button) => {
  // 用户确认对话框
  try {
    await ElMessageBox.confirm(
      `确定要执行"${button.label}"操作吗？这将基于当前图片生成新的变体。`,
      '确认操作',
      {
        confirmButtonText: '确认执行',
        cancelButtonText: '取消',
        type: 'info',
      }
    )
  } catch {
    return // 用户取消操作
  }

  // 执行操作
  try {
    const loading = ElLoading.service({
      lock: true,
      text: `正在执行 ${button.label}...`,
      background: 'rgba(0, 0, 0, 0.7)',
    })

    // 调用MJ命令执行API
    const result = await executeMjCommand({
      id: Number(image.id),
      customId: button.customId
    })

    loading.close()

    ElMessage.success(`${button.label} 操作已提交，请稍后查看生成结果`)
    
    // 刷新历史记录以显示新任务
    setTimeout(() => {
      loadDrawHistory()
    }, 1000)

    console.log('MJ命令执行结果:', result)
    
  } catch (error) {
    console.error('执行MJ操作失败:', error)
    ElMessage.error(`执行 ${button.label} 操作失败，请稍后重试`)
  }
}

// 显示所有按钮
const showAllButtons = (image) => {
  ElMessageBox({
    title: '选择操作',
    message: h('div', { class: 'grid grid-cols-2 gap-2' }, [
      ...image.buttons.map(button => 
        h('button', {
          class: 'px-3 py-2 text-sm bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors',
          onClick: () => {
            ElMessageBox.close()
            handleMjButton(image, button)
          }
        }, button.label || '操作')
      )
    ]),
    showCancelButton: true,
    confirmButtonText: '取消',
    cancelButtonText: '',
    beforeClose: (action, instance, done) => {
      done()
    }
  })
}
</script>
<style scoped>
:deep(.el-textarea__inner) {
  min-height: 120px;
}
:deep(.el-input-number__decrease),
:deep(.el-input-number__increase) {
  display: none;
}
:deep(.el-slider__runway.show-input) {
  margin-right: 0;
}
:deep(.el-dialog__header) {
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 15px;
}
:deep(.el-dialog__footer) {
  border-top: 1px solid #f0f0f0;
  padding-top: 15px;
}
.animate-spin {
  animation: spin 1s linear infinite;
}
@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
